<template>
    <div>

        <el-card>
            <el-row :gutter="10">
                <el-col :span="6">
                    <span style="font-size: 15px;margin-right: 5px">屏蔽词:</span>
                    <el-input style="width: 200px" v-model="searchWord" placeholder="请输入屏蔽词"></el-input>
                </el-col>

                <el-col :span="6">
                    <span style="font-size: 15px;margin-right: 5px">状态:</span>
                    <el-select style="width: 200px" v-model="searchStatus" placeholder="请选择" clearable>
                        <el-option
                                v-for="item in statuss"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>

                <el-col :span="8">
                    <span style="font-size: 15px;margin-right: 5px">创建时间:</span>
                    <el-date-picker
                            style="width: 300px"
                            v-model="searchCreateTime"
                            type="daterange"
                            align="right"
                            unlink-panels
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="handleDateChange"
                            :picker-options="pickerOptionsSearch">
                    </el-date-picker>
                </el-col>
                <el-col :span="3">
                    <span style="margin-right: 10px">
                        <el-button type="primary"
                                   @click="searchByManyCondition" plain> 搜 索
                        </el-button>
                    </span>
                    <span><el-button @click="resetCondition"> 重 置</el-button></span>
                </el-col>
            </el-row>
        </el-card>

        <el-card style="width: 100%; ">

            <!--          屏蔽词信息    标题-->
            <div slot="header" class="clearfix">
                <span style="font-weight: bold;font-size: 18px">屏蔽词信息</span>
                <el-button style="float: right;margin-right: 20px" type="primary" plain @click="showAddBlockedWord">
                    添加屏蔽词
                </el-button>

                <el-dialog title="添加屏蔽词" :visible.sync="dialogVisible_add">
                    <el-form :model="add_blockedWord" size="medium" :rules="rules" ref="addBlockedWordRef"
                             :validate-on-rule-change="false">

                        <el-form-item prop="word" label="屏蔽词" label-width="100px">
                            <el-input v-model="add_blockedWord.word" placeholder="请输入屏蔽词"></el-input>
                        </el-form-item>

                        <el-form-item prop="createTime" label="创建时间" label-width="100px">
                            <el-date-picker
                                    v-model="add_blockedWord.createTime"
                                    type="datetime"
                                    placeholder="选择日期时间"
                                    align="right"
                                    :picker-options="pickerOptions">
                            </el-date-picker>
                        </el-form-item>

                        <el-form-item prop="status" label="状态" label-width="100px">
                            <el-select v-model="add_blockedWord.status" placeholder="请选择状态">
                                <el-option
                                        v-for="item in statuss"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>

                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button type="warning" @click="resetAddBlockedWord"> 重 置</el-button>
                        <el-button @click="cancelDialog_addBlockedWord"> 取 消</el-button>
                        <el-button type="primary" @click="handleEdit_addBlockedWord"> 确 定</el-button>
                    </div>

                </el-dialog>

                <el-button style="float: right;margin-right: 10px" type="danger" @click="deleteSelectComments"> 删除选中
                </el-button>
                <el-button style="float: right;margin-right: 10px" type="primary" plain @click="selectAll"> 查询所有屏蔽词
                </el-button>

                <!-- 删除屏蔽词信息的弹窗 -->
                <el-dialog
                        title="提示"
                        :visible.sync="dialogVisible_deleteSelect"
                        width="30%">
                    <span>真的要删除选中的所有信息吗？</span>
                    <span slot="footer" class="dialog-footer">
                                        <el-button @click="dialogVisible_deleteSelect = false">取 消</el-button>
                                        <el-button type="danger" @click="handleDeleteBlockedWords">确 定</el-button>
                                    </span>
                </el-dialog>

            </div>

            <template>
                <el-table height="400"
                          :header-cell-style="{fontSize: '14px','text-align':'center'}"
                          :cell-style="{'text-align':'center'}"
                          :data="blockedWordList"
                          @selection-change="handleSelectCodeForTicket"
                          stripe
                          style="width: 100%">
                    <el-table-column
                            type="selection"
                    >
                    </el-table-column>
                    <el-table-column label="序号" type="index" align="center"></el-table-column>
                    <el-table-column prop="word" label="屏蔽词" show-overflow-tooltip
                    ></el-table-column>

                    <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip
                    ></el-table-column>

                    <el-table-column label="状态">
                        <template slot-scope="scope">
                            <el-tag type="warning" v-if="scope.row.status===0">失效中</el-tag>
                            <el-tag type="success" effect="dark" v-if="scope.row.status===1">生效中</el-tag>
                        </template>
                    </el-table-column>


                    <el-table-column label="操作">

                        <template slot-scope="scope">

                            <el-button type="primary" icon="el-icon-edit" circle
                                       @click="handleEditButton(scope.row)"></el-button>

                            <!--         删除按钮    -->
                            <el-button type="danger" icon="el-icon-delete" circle
                                       @click="handleDeleteButton(scope.row)"></el-button>

                            <!-- 删除屏蔽词信息的弹窗 -->
                            <el-dialog
                                    title="提示"
                                    :visible.sync="dialogVisible_delete"
                                    width="30%">
                                <span style="display: flex;">真的要删除这条信息吗？</span>
                                <span slot="footer" class="dialog-footer">
                                        <el-button @click="dialogVisible_delete = false">取 消</el-button>
                                        <el-button type="danger" @click="handleDeleteBlockedWord">确 定</el-button>
                                    </span>
                            </el-dialog>

                            <!--    修改-->
                            <el-dialog title="修改屏蔽词信息" :visible.sync="dialogFormVisible_edit">
                                <el-form :model="edit_blockedWord" size="medium" :rules="rules" ref="editBlockedWordRef"
                                         :validate-on-rule-change="false">

                                    <el-form-item prop="word" label="屏蔽词" label-width="100px">
                                        <el-input v-model="edit_blockedWord.word"
                                                  placeholder="请输入屏蔽词"></el-input>
                                    </el-form-item>

                                    <el-form-item prop="createTime" label="创建时间" label-width="100px">
                                        <el-date-picker
                                                v-model="edit_blockedWord.createTime"
                                                type="datetime"
                                                placeholder="选择日期时间"
                                                align="right"
                                                :picker-options="pickerOptions">
                                        </el-date-picker>
                                    </el-form-item>

                                    <el-form-item prop="status" label="状态" label-width="100px">
                                        <el-select v-model="edit_blockedWord.status" placeholder="请选择状态"
                                                   style="float: left;margin-left: 50px">
                                            <el-option
                                                    v-for="item in statuss"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>


                                </el-form>


                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="cancelDialog_edit">取 消</el-button>
                                    <el-button type="primary" @click="handleEdit">确 定</el-button>
                                </div>

                            </el-dialog>

                        </template>

                    </el-table-column>

                </el-table>

            </template>

            <el-pagination
                    style="float: right;margin: 20px 0"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next"
                    background
                    :total="total">
            </el-pagination>
        </el-card>

    </div>
</template>

<script>
import {defineComponent} from 'vue'
import dateUtil from '@/utils/dateUtil';

export default defineComponent({
    name: "BlockedWord",
    data() {
        return {
            dialogVisible_delete: false,        // 删除按钮弹出框
            dialogVisible_deleteSelect: false,  // 选中删除按钮弹出框
            dialogFormVisible_edit: false,
            dialogVisible_add: false,      // 添加屏蔽词按钮弹出框
            searchWord: '',
            // searchUserId: '',
            // searchProductName: '',
            // searchProductId: '',
            searchCreateTime: '',
            searchStartTime: '',
            searchEndTime: '',
            searchStatus: '',


            edit_blockedWord: {},
            edit_createTime: '',
            add_blockedWord: {},

            blockedWordList: [],
            blockedWordDelete: {},             // 存储被删除屏蔽词的id
            blockedWordDeletes: [],                 // 存储被选中屏蔽词的id

            userRestaurants: [],            // 存储所有所有用户
            productRestaurants: [],          // 存储所有所有屏蔽词名称

            // 搜素的日期选择器
            pickerOptionsSearch: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },

            statuss: [{             // 存储所有状态
                value: 0,
                label: '失效'
            }, {
                value: 1,
                label: '生效'
            }],
            pickerOptions: {
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },

            currentPage: 1,          // 当前页码
            pageSizes: [5, 10, 50, 100], // 每页显示条数
            pageSize: 5,             // 每页显示条数
            total: 0,                // 屏蔽词总数


            rules: {
                word: [
                    {required: true, message: '请输入屏蔽词', trigger: 'blur'},
                ],
                createTime: [
                    {required: true, message: '请输入创建时间', trigger: 'blur'}
                ],
                status: [
                    {required: true, message: '请选择状态', trigger: 'change'}
                ],
            },

        }
    },
    mounted() {
        this.searchByManyConditionNoMsg()
    },
    methods: {

        handleEdit_addBlockedWord() {
            // 格式化时间
            this.add_blockedWord.createTime = dateUtil.formatDate(this.add_blockedWord.createTime)
            // 输入检验
            this.$refs['addBlockedWordRef'].validate((valid) => {
                if (valid) {
                    // 校验通过，添加屏蔽词
                    this.$request.post('/blockedWord/add', this.add_blockedWord).then(res => {
                        this.dialogVisible_add = false;
                        this.add_blockedWord = {}
                        if (res.code === '200') {
                            this.$message.success('添加成功')
                            this.searchByManyConditionNoMsg()
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                } else {
                    this.$message.error('请输入完整信息')
                }
            })
        },
        // 取消添加屏蔽词
        cancelDialog_addBlockedWord() {
            this.dialogVisible_add = false;
        },
        // 重置添加的信息
        resetAddBlockedWord() {
            this.add_blockedWord = {}
        },
        // 显示添加屏蔽词的弹出框
        showAddBlockedWord() {
            this.clearcheck('addBlockedWordRef')
            this.dialogVisible_add = true;
            this.add_blockedWord = {}
        },


        handleEdit() {

            // 如果时间没变不处理
            if (this.edit_blockedWord.createTime === null || this.edit_blockedWord.createTime === '' || this.edit_blockedWord.createTime === undefined) {
                this.$message.info('时间格式错误！')
                return
            }
            if (this.edit_blockedWord.createTime !== this.edit_createTime) {
                this.edit_blockedWord.createTime = dateUtil.formatDate(this.edit_blockedWord.createTime)
            }
            // 输入检验
            this.$refs['editBlockedWordRef'].validate((valid) => {
                if (valid) {
                    // 校验通过
                    this.$request.put('/blockedWord/update', this.edit_blockedWord).then(res => {
                        this.dialogFormVisible_edit = false;
                        if (res.code === '200') {
                            this.$message.success('修改成功');
                            this.edit_blockedWord = {}
                            // 重新加载数据
                            this.searchByManyConditionNoMsg()
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                } else {
                    this.$message.error('请输入完整信息')
                }
            })
        },
        // 取消修改信息
        cancelDialog_edit() {
            this.dialogFormVisible_edit = false;
            this.edit_blockedWord = {}
        },
        handleEditButton(blockedWord) {
            this.clearcheck('editBlockedWordRef')
            // 将当前行的屏蔽词数据传入form中
            this.edit_blockedWord = JSON.parse(JSON.stringify(blockedWord));
            this.edit_createTime = JSON.parse(JSON.stringify(blockedWord.createTime))
            // 显示弹窗
            this.dialogFormVisible_edit = true;
        },

        // 解决elementUI中时间选择器的问题，使得时间选择器可以清空
        handleDateChange(value) {
            // 当日期改变时的处理函数
            // 在这里你可以根据需要处理日期的值
            // 例如，如果不想让清空操作将日期设置为null，可以在这里进行判断
            if (value === null) {
                // 当清空日期时，不更新pickedDate，保持原值
                // 如果需要在清空时设置日期为特定值（比如空字符串），可以在此处设置
                this.searchCreateTime = ''
                return;
            }
            // 在其他情况下，将值更新为选择的日期
            this.searchCreateTime = value;
        },

        // 搜索
        searchByManyCondition() {
            // 处理时间段信息
            if (this.searchCreateTime !== '' && this.searchCreateTime !== null) {
                this.searchStartTime = dateUtil.formatDate(this.searchCreateTime[0])
                this.searchEndTime = dateUtil.formatDate(this.searchCreateTime[1])
            }
            // else {
            //     this.searchStartTime = '1000-01-01 00:00:00'
            //     this.searchEndTime = '9999-12-31 23:59:59'
            // }
            let blockedWord = {}
            blockedWord.word = this.searchWord
            blockedWord.status = this.searchStatus
            blockedWord.startTime = this.searchStartTime
            blockedWord.endTime = this.searchEndTime
            let obj = {}
            obj.blockedWord = blockedWord
            obj.currentPage = this.currentPage
            obj.pageSize = this.pageSize
            this.$request.post('/blockedWord/getByManyConditionInPage', obj).then(res => {
                if (res.code === '200') {
                    this.blockedWordList = res.data.list
                    this.total = res.data.total
                    this.$message.success('查询成功')
                } else {
                    this.$message
                        .error('查询失败')
                }
            })

        },
        searchByManyConditionNoMsg() {
            // 处理时间段信息
            if (this.searchCreateTime !== '' && this.searchCreateTime !== null) {
                this.searchStartTime = dateUtil.formatDate(this.searchCreateTime[0])
                this.searchEndTime = dateUtil.formatDate(this.searchCreateTime[1])
            }
            // else {
            //     this.searchStartTime = '1000-01-01 00:00:00'
            //     this.searchEndTime = '9999-12-31 23:59:59'
            // }
            let blockedWord = {}
            blockedWord.word = this.searchWord
            blockedWord.status = this.searchStatus
            blockedWord.startTime = this.searchStartTime
            blockedWord.endTime = this.searchEndTime
            let obj = {}
            obj.blockedWord = blockedWord
            obj.currentPage = this.currentPage
            obj.pageSize = this.pageSize
            this.$request.post('/blockedWord/getByManyConditionInPage', obj).then(res => {
                if (res.code === '200') {
                    this.blockedWordList = res.data.list
                    this.total = res.data.total
                } else {
                    this.$message
                        .error('查询失败')
                }
            })

        },
        // 重置搜索
        resetCondition() {
            this.searchWord = ''
            this.searchStartTime = ''
            this.searchEndTime = ''
            this.searchCreateTime = ''
            this.searchStatus = ''
            this.searchByManyConditionNoMsg()
        },

        // currentPage 改变时会触发
        handleCurrentChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.currentPage = val;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },
        //  pageSize 改变时会触发
        handleSizeChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.pageSize = val;
            this.currentPage = 1;

            // 发送请求获取相应数量的数据
            this.searchByManyConditionNoMsg()
        },

        // 删除选中二次提醒
        deleteSelectComments() {
            // 显示二次提醒弹窗
            this.dialogVisible_deleteSelect = true;
        },

        // 查询所有屏蔽词
        selectAll() {
            this.resetCondition()
        },

        // 删除选中二次确认
        handleDeleteBlockedWords() {
            this.dialogVisible_deleteSelect = false;

            console.log(this.blockedWordDeletes)
            if (this.blockedWordDeletes.length > 0) {
                // 删除选中
                this.$request.post('/blockedWord/deleteList', this.blockedWordDeletes).then(res => {
                    if (res.code === '200') {
                        this.$message.success('删除成功');
                        // 刷新数据
                        this.searchByManyConditionNoMsg()
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$message.info('请选择要删除的屏蔽词');
            }
        },

        // 并存储到 blockedWordDeletes 数组中
        handleSelectCodeForTicket(val) {
            this.blockedWordDeletes = val
        },

        // 删除按钮二次提醒
        handleDeleteButton(blockedWordDelete) {
            this.dialogVisible_delete = true
            this.blockedWordDelete = blockedWordDelete
        },

        // 删除当前屏蔽词
        handleDeleteBlockedWord() {
            this.dialogVisible_delete = false;
            console.log(this.blockedWordDelete)
            this.$request.delete('/blockedWord/delete/' + this.blockedWordDelete.id).then(res => {
                if (res.code === '200') {
                    this.$message.success('删除成功');
                    this.blockedWordDelete = {}
                    // 重新加载数据
                    this.searchByManyConditionNoMsg()
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 移除表单的校验
        clearcheck(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate()
            }
        },
    }
})
</script>


<style scoped>

</style>